﻿#include "statistics.h"
#include "ui_statistics.h"

Statistics::Statistics(QWidget *parent, const QString &month,
                       const QStringList &publishers) :
    QDialog(parent),
    currentMonth(month),
    _publishers(publishers),
    ui(new Ui::Statistics)
{
    ui->setupUi(this);

    table=STAT_JOURNAL;
    index_table=ST_JOURNAL;
    updateFlag=false;
    model=new QStandardItemModel(this);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);
    ui->listView->setEditTriggers(QListView::NoEditTriggers);

    updateHistory();
}

Statistics::~Statistics()
{
    delete ui;
}

void Statistics::updateHistory()
{
    QStringList items;
    QSqlQuery query;
    query.exec(QString("select month_ from %1 group by month_").arg(table));
    while (query.next()) {
        QString date=query.value(0).toString();
        if(date.isEmpty())
            continue;

        items.append(date);
    }
    if(!items.isEmpty())
        listModel->setStringList(items);
}

void Statistics::do_order()
{
    QMap<QString,int> orders;

    QSqlQuery query;
    query.exec(QString("select name,COUNT(name) from %1 where month_='%2' group by name")
               .arg(index_table)
               .arg(currentMonth));
    while (query.next()) {
        QString name=query.value(0).toString();
        if(name.isEmpty())
            continue;

        int order=query.value(1).toInt();
        orders.insert(name,order);
    }

    if(orders.isEmpty())
    {
        ui->status->setText(QStringLiteral("无法获取到有效数据！"));
        return;
    }

    if(_publishers.size() != orders.size())
    {
        ui->status->setText(QStringLiteral("数据不匹配，请更新数据！"));
        // return;
    }

    foreach (QString publisher, _publishers) {
        QList<QStandardItem *> item;
        item.append(new QStandardItem(publisher));
        int order=orders.value(publisher);
        item.append(new QStandardItem(QString::number(order)));
        model->appendRow(item);
    }

    if(model->rowCount() > 0)
    {
        model->setHeaderData(NAME_COL,Qt::Horizontal,QStringLiteral("姓名"));
        model->setHeaderData(ORDER_COL,Qt::Horizontal,QStringLiteral("提交数"));
    }
}

void Statistics::do_rank()
{
    int act_num=1;    //实际数量
    int ex_num=0;     //预期数量
    QSqlQuery query;
    query.exec(QString("select COUNT(name) from %1 where month_='%2' AND name IS NOT NULL")
               .arg(index_table)
               .arg(currentMonth));
    if(query.next())
        act_num=query.value(0).toInt();

    query.exec(QString("select COUNT(name) from %1 where month_='%2' AND rank IS NOT NULL")
               .arg(index_table)
               .arg(currentMonth));
    if(query.next())
        ex_num=query.value(0).toInt();

    QString status;
    if(act_num != ex_num)
    {
        status=QStringLiteral("提交数： ") + QString::number(act_num)
                + QStringLiteral(" 评级数： ") + QString::number(ex_num)
                + QStringLiteral(" 评级未完成，无法进行评分！");
        ui->status->setText(status);
        ui->btn_save->setEnabled(false);
        // return;
    }

    status=QStringLiteral("提交数： ") + QString::number(act_num);
    ui->status->setText(status);

    QMap<QString,int> ranks;
    query.exec(QString("select name,SUM(rank) from %1 where month_='%2' group by name")
               .arg(index_table)
               .arg(currentMonth));
    while (query.next()) {
        QString name=query.value(0).toString();
        if(name.isEmpty())
            continue;

        int rank=query.value(1).toInt();
        ranks.insert(name,rank);
    }

    if(ranks.isEmpty())
    {
        ui->status->setText(QStringLiteral("无法获取到有效数据！"));
        return;
    }

    if(_publishers.size() != ranks.size())
    {
        ui->status->setText(QStringLiteral("数据不匹配，请更新数据！"));
        // return;
    }

    QList<QStandardItem *> items;
    foreach (QString publisher, _publishers) {
        int rank=ranks.value(publisher);
        items.append(new QStandardItem(QString::number(rank)));
    }

    if(!items.isEmpty())
    {
        model->insertColumn(RANK_COL,items);
        model->setHeaderData(RANK_COL,Qt::Horizontal,QStringLiteral("评分"));
    }
}

void Statistics::on_btn_generate_clicked()
{
    if(_publishers.isEmpty())
        return;

    if(model->rowCount() != 0)
        model->clear();

    do_order();
    do_rank();
    //ui->btn_generate->setEnabled(false);
}

bool Statistics::insertItem(const QString &id_,
                            const QString &name, const QString &p_submit,
                            const QString &p_rank)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 values (?,?,?,?,?)")
                  .arg(table));
    query.addBindValue(id_);
    query.addBindValue(currentMonth);
    query.addBindValue(name);
    query.addBindValue(p_submit);
    query.addBindValue(p_rank);
    if(!query.exec())
    {
        qDebug() << query.lastError().text();
        return false;
    }
    else
        return true;
}

bool Statistics::updateItem(const QString &id_, const QString &p_submit,
                            const QString &p_rank)
{
    QSqlQuery query;
    QString sql=QString("update %1 set p_submit='%2',p_rank='%3' where id_='%4'")
            .arg(table)
            .arg(p_submit)
            .arg(p_rank)
            .arg(id_);
    if(!query.exec(sql))
    {
        qDebug() << query.lastError().text();
        return false;
    }
    else
        return true;
}

void Statistics::on_btn_save_clicked()
{
    int rowCount=model->rowCount();
    if(rowCount < 1)
        return;

    QSqlQuery query;
    query.exec(QString("select id_ from %1 where month_='%2'")
               .arg(table)
               .arg(currentMonth));
    if(query.next())
        updateFlag=true;
    else
        updateFlag=false;

    int insertNum=0;
    int updateNum=0;

    for(int i=0;i < rowCount;i++)
    {
        QString suffix="0" + QString::number(i);
        if(i<10)
            suffix="0" + suffix;

        QString date=currentMonth;
        QString id=date.remove("-") + suffix;
        QString name=model->index(i,0).data().toString();
        QString p_submit=model->index(i,1).data().toString();
        QString p_rank=model->index(i,2).data().toString();

        if(updateFlag)
        {
            if(updateItem(id,p_submit,p_rank))
                updateNum+=1;
        }
        else
        {
            if(insertItem(id,name,p_submit,p_rank))
                insertNum+=1;
        }
    }

    if(updateFlag)
    {
        if(updateNum == 0)
            ui->status->setText(QStringLiteral("异常情况，无法更新数据！"));
        else if(updateNum == rowCount)
            ui->status->setText(QStringLiteral("记录更新成功！"));
        else
            ui->status->setText(QStringLiteral("记录部分更新成功！"));
    }
    else
    {
        if(insertNum == 0)
            ui->status->setText(QStringLiteral("异常情况，无法保存数据！"));
        else if(insertNum == rowCount)
        {
            ui->status->setText(QStringLiteral("记录保存成功！"));
            updateHistory();
        }
        else
        {
            ui->status->setText(QStringLiteral("记录部分保存成功！"));
            updateHistory();
        }
    }
    ui->btn_save->setEnabled(false);
}

void Statistics::updateView(const QString &month)
{
    if(month.isEmpty())
        return;

    if(model->rowCount() != 0)
        model->clear();

    QSqlQuery query;
    query.exec(QString("select name,p_submit,p_rank from %1 where month_='%2'")
               .arg(table)
               .arg(month));
    while (query.next()) {
        QString name=query.value(0).toString();
        QString p_submit=query.value(1).toString();
        QString p_rank=query.value(2).toString();

        QList<QStandardItem *> item;
        item.append(new QStandardItem(name));
        item.append(new QStandardItem(p_submit));
        item.append(new QStandardItem(p_rank));
        model->appendRow(item);
    }

    if(model->rowCount() > 0)
    {
        model->setHeaderData(NAME_COL,Qt::Horizontal,QStringLiteral("姓名"));
        model->setHeaderData(ORDER_COL,Qt::Horizontal,QStringLiteral("提交数"));
        model->setHeaderData(RANK_COL,Qt::Horizontal,QStringLiteral("评分"));
    }
}

void Statistics::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        if(ui->btn_generate->isEnabled())
            ui->btn_generate->setEnabled(false);

        if(ui->btn_save->isEnabled())
            ui->btn_save->setEnabled(false);

        QString date=index.data().toString();
        updateView(date);
    }
}
